package asionreachel.cn.smarthomedemo.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import asionreachel.cn.smarthomedemo.base.Common;
import asionreachel.cn.smarthomedemo.thread.JFamilyClientApp;


/**
 * Created by Simon(lyd) on 2016/9/27 14:48.
 * 描述：App工具类
 */

public class AppUtils {

    /**
     * 广播名(plan错误信息和Toast信息)
     */
    public static final String Error = "this is app plan error";

    /**
     * 广播名（RDSearch）回调
     */
    public static final String RDSearch = "this is app RDSearch";

    /**
     * 保存短信发送时间
     */
    public static long codeTime = 0;

    // 用于电话验证码存放倒计时时间
    public static HashMap<String, Long> phoneMap;

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取状态栏的高度
     *
     * @return
     */
    public static int getStatusBarHeight() {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, sbar = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            sbar = JFamilyClientApp.getInstance().getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return sbar;
    }

    /**
     * 判断字符串是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }

    /** 获取wifi名 */
    public static String getWifiName() {
        if(!isWifiConnected(JFamilyClientApp.getInstance())){
            Common.showToast("请连接WiFi");
            return "";
        }
        WifiManager wifiMgr = (WifiManager)JFamilyClientApp.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiMgr.getConnectionInfo();
        String wifiId = info != null ? info.getSSID().toString() : "";
        return wifiId.replaceAll("\"", "");
    }

    public static String getWifiBSSID() {
        if(!isWifiConnected(JFamilyClientApp.getInstance())){
            Common.showToast("请连接WiFi");
            return "";
        }
        WifiManager wifiMgr = (WifiManager)JFamilyClientApp.getInstance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiMgr.getConnectionInfo();
        String wifiId = info != null ? info.getBSSID() : "";
        return wifiId.replaceAll("\"", "");
    }

    //是否连接WIFI
    public static boolean isWifiConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(wifiNetworkInfo.isConnected()) {
            return true ;
        }
        return false ;
    }
    /**
     * 获取GMT时间
     */
    public static int getCurrentTimeZone() {
        TimeZone tz = TimeZone.getDefault();
        Mlog.e("时间: " + tz.getRawOffset());
        return Integer.parseInt(createGmtOffsetString(true, true, tz.getRawOffset()));
    }

    public static String createGmtOffsetString(boolean includeGmt,
                                               boolean includeMinuteSeparator, int offsetMillis) {
        int offsetMinutes = offsetMillis / 60000;
        String sign = "";
        if (offsetMinutes < 0) {
            sign = "-";
            offsetMinutes = -offsetMinutes;
        }
        StringBuilder builder = new StringBuilder(9);
        if (includeGmt) {
//            builder.append("GMT");
        }
        builder.append(sign);
        appendNumber(builder, 2, offsetMinutes / 60);
        if (includeMinuteSeparator) {
//            builder.append(':');
        }
//        appendNumber(builder, 2, offsetMinutes % 60);
        return builder.toString();
    }

    private static void appendNumber(StringBuilder builder, int count, int value) {
        String string = Integer.toString(value);
        for (int i = 0; i < count - string.length(); i++) {
            builder.append('0');
        }
        builder.append(string);
    }



    /**
     * 判断是否有外网连接（普通方法不能判断外网的网络是否连接，比如连接上局域网）
     * @return
     */
    public static final boolean ping(String ip) {

        String result = null;
        try {
//            String ip = "www.baidu.com";// ping 的地址，可以换成任何一种可靠的外网
            Process p = Runtime.getRuntime().exec("ping -c 2 -w 100 " + ip);// ping网址2次
            // 读取ping的内容，可以不加
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("是否能正常使用网络", "result = " + result);
        }
        return false;
    }

    public static final boolean isPing(){
        String ip[] = {"www.baidu.com","www.tmall.com","www.qq.com"};
        if(ping(ip[0])){  //判断是否能连接上百度
            return true;
        }

        if(ping(ip[1])){  //判断是否能连接上天猫
            return true;
        }

        if(ping(ip[2])){  //判断是否能连接上腾讯
            return true;
        }

        return false;
    }
}
